package it.polimi.traveldream.ejb;

import java.util.ArrayList;
import java.util.List;

import it.polimi.traveldream.ejb.management.VoloDTO;
import it.polimi.traveldream.ejb.management.VoloMgr;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class BeanVolo implements VoloMgr {
	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;
	
	private BeanAeroporto beanAeroporto; 

	@Override
	public void save(VoloDTO volo) {
		Query query = em.createNamedQuery(Aeroporto.FINDIATA,Aeroporto.class);
		query.setParameter(1,volo.getAeroportoArrivo());
		Aeroporto aeroportoArr = (Aeroporto) query.getResultList().get(0);
		query.setParameter(1,volo.getAeroportoPartenza());
		Aeroporto aeroportoPar = (Aeroporto) query.getResultList().get(0);
		Volo voloNew = new Volo(volo, aeroportoArr, aeroportoPar);
		em.persist(voloNew);
		
	}

	@Override
	public void update(VoloDTO volo) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public VoloDTO getVolo() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public VoloDTO convertToDTO(Volo volo) {
		VoloDTO voloDTO = new VoloDTO();
		voloDTO.setIdVolo(volo.getIdVolo());
		voloDTO.setNumVolo(volo.getNumVolo());
		voloDTO.setPostiRimanenti(volo.getPostiRimanenti());
		voloDTO.setPrezzo(volo.getPrezzo());
		voloDTO.setCompagnia(volo.getCompagnia());
		voloDTO.setAeroportoArrivo(volo.getAeroportoArrivo().getCodIata());
		voloDTO.setAeroportoPartenza(volo.getAeroportoPartenza().getCodIata());
		voloDTO.setData(volo.getData());
		return voloDTO;
	}

	@Override
	public List<VoloDTO> getListaVoli() {
		List<Volo> list = em.createNamedQuery(Volo.FINDALL,Volo.class).getResultList();
		List<VoloDTO> list2 = new ArrayList<VoloDTO>(); 
		for (Volo a: list) {
			list2.add(convertToDTO(a));
		}
		return list2;
	}
	
	@Override
	public void elimina(VoloDTO vol){
		Query query=em.createNamedQuery(Volo.DELETE,Volo.class);
		System.out.println("HERE " + vol.getIdVolo());
		query.setParameter(1,vol.getIdVolo());
		query.executeUpdate();
		
	}

	@Override
	public VoloDTO getVoloById(int id) {
		Query query=em.createNamedQuery(Volo.FINDID,Volo.class);
		query.setParameter(1,id);
		Volo volo = (Volo) query.getResultList().get(0);
		return convertToDTO(volo);
	}
}
